package top.malaoshi.webmvc.parameter;

import com.fasterxml.jackson.databind.ObjectMapper;
import top.malaoshi.util.StringUtil;
import top.malaoshi.webmvc.exception.ParameterTypeMatchValueException;
import top.malaoshi.webmvc.exception.RequestParamResolverException;
import top.malaoshi.webmvc.info.MethodsArgumentInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * request中的数据是json格式，解析成相应的对象
 */
public class JsonResolver implements RequestParamAndMethodArgsResolver {
    @Override
    public Object resolver(HttpServletRequest request,
                           HttpServletResponse response ,
                           MethodsArgumentInfo mai) {


        checkContentType(request);
        Class type = mai.getType();

        try{
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = request.getReader();
            char[]buff = new char[1024];
            int len;
            while((len = reader.read(buff)) != -1) {
                sb.append(buff,0, len);
            }
            String json = sb.toString();
            if(mai.getRequestBody().required()){
                if(json == null || "".equals(json)){
                    String msg = String.format("@RequestBody注解中，required为true，从request取出的数据不能是空");
                    throw new ParameterTypeMatchValueException(msg);
                }
            }
            ObjectMapper mapper = new ObjectMapper();
            Object ret = mapper.readValue(json, type);
            return ret;
        }catch (IOException e) {
            throw new RequestParamResolverException(e);
        }

    }
    private void checkContentType(HttpServletRequest request){
        String contentType = request.getHeader("Content-Type");
        if(contentType!=null && !"".equals(contentType)){
            if(contentType.startsWith("application/json")){
                // 允许解析
            }else{
                String msg = String.format("请求头 Content-Type:"+contentType+"，不能解析JSON");
                throw new ParameterTypeMatchValueException(msg);
            }
        }
        //        else{
//            String msg = String.format("请求中");
//            throw new ParameterTypeMatchValueException(msg);
//        }
    }
}
